﻿var newCreate = false;

//INDEXED DB FUNCTIONS
function createDB() {
    // Create the request to open the database, named BookDB. If it doesn't exist, create it and immediately
    // upgrade to version 1.
    var dbRequest = window.indexedDB.open("AppDB", 1);

    // Add asynchronous callback functions
    dbRequest.onerror = function () { WinJS.log && WinJS.log("Error creating database.", "sample", "error"); };
    dbRequest.onsuccess = function (evt) { dbSuccess(evt); };
    dbRequest.onupgradeneeded = function (evt) { dbVersionUpgrade(evt); };
    dbRequest.onblocked = function () { WinJS.log && WinJS.log("Database create blocked.", "sample", "error"); };

    // Reset the flag that indicates whether this is a new creation request. 
    // Assume that the database was previously created.
    newCreate = false;
}

function deleteDB() {
    // Close and clear the handle to the database, held in the parent SdkSample namespace.
    if (SdkSample.db) {
        SdkSample.db.close();
    }
    SdkSample.db = null;
    var dbRequest = window.indexedDB.deleteDatabase("AppDB");
    dbRequest.onerror = function () { WinJS.log && WinJS.log("Error deleting database.", "sample", "error"); };
    dbRequest.onsuccess = function () { WinJS.log && WinJS.log("Database deleted.", "sample", "status"); };
    dbRequest.onblocked = function () {
        WinJS.log && WinJS.log("Database delete blocked.", "sample", "error");
    };
}

// Whenever an IndexedDB is created, the version is set to "", but can be immediately upgraded by calling createDB. 
function dbVersionUpgrade(evt) {
    // If the database was previously loaded, close it. 
    // Closing the database keeps it from becoming blocked for later delete operations.
    if (SdkSample.db) {
        SdkSample.db.close();
    }
    SdkSample.db = evt.target.result;

    // Get the version update transaction handle, since we want to create the schema as part of the same transaction.
    var txn = evt.target.transaction;

    // Create the books object store, with an index on the book title. Note that we set the returned object store to a variable
    // in order to make further calls (index creation) on that object store.
    var userInfoStore = SdkSample.db.createObjectStore("userInfo", { keyPath: "id" });
    userInfoStore.createIndex("fb_id", "fb_id", { unique: true });
    userInfoStore.createIndex("name", "name", { unique: false });

    // Create the authors object store.
    var feedbackStore = SdkSample.db.createObjectStore("feedback", { keyPath: "id", autoincrement: true });
    // Create the book checkout status object store. Note that new object stores can only be created/deleted as part of the version change.
    // transaction that we're adding to in this function.
    //SdkSample.db.createObjectStore("checkout", { keyPath: "id" });

    // Once the creation of the object stores is finished (they are created asynchronously), log success.
    txn.oncomplete = function () { WinJS.log && WinJS.log("Database schema created.", "sample", "status"); };
    newCreate = true;
}

function dbSuccess(evt) {
    // Log whether the app tried to create the database when it already existed. 
    if (!newCreate) {
        // Close this additional database request
        var db = evt.target.result;
        db.close();
        WinJS.log && WinJS.log("Database schema already exists.", "sample", "error");
        return;
    }
}

//HELPER FUNCTIONS
//helper function for indexed database operations
function indexedDataBaseOp(toCall, results, currentApp) {

    var dbRequest = window.indexedDB.open("AppDB", 1);

    // Add asynchronous callback functions
    dbRequest.onerror = function () { WinJS.log && WinJS.log("Error opening database.", "sample", "error"); };
    dbRequest.onsuccess = function (evt) { dbSuccess(evt); };
    dbRequest.onupgradeneeded = function (evt) { WinJS.log && WinJS.log("Database wrong version.", "sample", "error"); if (SdkSample.db) { SdkSample.db.close(); } };
    dbRequest.onblocked = function () { WinJS.log && WinJS.log("Database access blocked.", "sample", "error"); };

    function dbSuccess(evt) {
        // If the database was previously loaded, close it... this keeps the database from becoming blocked for later deletes
        if (SdkSample.db) {
            SdkSample.db.close();
        }
        SdkSample.db = evt.target.result;
        if (SdkSample.db.objectStoreNames.length === 0) {
            WinJS.log && WinJS.log("Database schema does not exist. Complete the first scenario before continuing.", "sample", "error");
            SdkSample.db.close();
            SdkSample.db = null;
            window.indexedDB.deleteDatabase("AppDB", 1);
        } else {
            if (currentApp) {
                toCall(evt, results, currentApp);
            }
            else
            {
                toCall(evt, results);
            }
        }
    }
}

//helper function for azure mobile service table updation
function upDateAzureTable(id, result) {
    azure_userInfoTable.where({ fb_id: id }).read().done(function (results2) {
        result.azureId = results2[0].id;

        var entry;
        if (result.azureId) {
            entry = {
                id: result.azureId,
                name: result.name,
                id_azure: result.id,
                db_isactive: result.db_IsActive,
                db_istrial: result.db_IsTrial,
                fb_id: result.fb_id,
                total_shares: result.Total_Shares,
                trialStartDate: result.trialStartDate,
                trialEndDate: result.trialEndDate
            }
            azure_userInfoTable.update(entry).done(updateLocalStore);
        }
        else {
            entry = {
                name: result.name,
                id_azure: result.id,
                db_isactive: result.db_IsActive,
                db_istrial: result.db_IsTrial,
                fb_id: result.fb_id,
                total_shares: result.Total_Shares,
                trialStartDate: result.trialStartDate,
                trialEndDate: result.trialEndDate
            }
            azure_userInfoTable.insert(entry).done(updateLocalStore);
        }
    });

    function updateLocalStore() {

        var txn2 = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn2.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn2.onerror = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        txn2.onabort = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        var userInfoStore2 = txn2.objectStore("userInfo");
        userInfoStore2.put(result);
    }
}


function updateLocalDb(evt, results) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            WinJS.log && WinJS.log("Database loaded from azure.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("Load from db failed", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("Load from db failed.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");
        var e; //entry in azure
        var i = 0;
        for (i = 0; i < results.length; i++) {
            e = {
                azureId: results[i].id,
                id: results[i].id_azure,
                name: results[i].name,
                db_IsActive: results[i].db_isactive,
                db_IsTrial: results[i].db_istrial,
                Total_Shares: results[i].total_shares,
                fb_id: results[i].fb_id,
                trialStartDate: results[i].trialstartdate,
                trialEndDate: results[i].trialenddate
            }
            userInfoStore.put(e);
        }
    }
}

function loadFromAzureToLocalDb() {
    azure_userInfoTable.read().done(function (results) {
        indexedDataBaseOp(updateLocalDb, results);
    });
}

function searchAndDelData(evt, response) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");

        var request = userInfoStore.delete(response.id);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }
        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            azure_userInfoTable.where({ fb_id: response.id }).read().done(function (results2) {
                if (results2.length > 0) {
                    azure_userInfoTable.del({
                        id: results2[0].id
                    }).done(function () {
                        /* Do something */
                        WinJS.log && WinJS.log("Account refresh made. You can start afresh.");                        
                    }, function (err) {
                        WinJS.log && WinJS.log("Error: " + err.message);
                    });
                }
            });
        };
    }
}

function searchData(evt, ids) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");
        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");

        var request = userInfoStore.get(ids[0]);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }
        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            if (result) {
                result.Total_Shares = result.Total_Shares + 1;
                if (result.db_IsTrial == false && result.db_IsActive == true) { //full license already bought                 

                    userInfoStore.put(result);

                    //Update azure mobile service table
                    upDateAzureTable(ids[0], result);
                            
                    WinJS.log && WinJS.log("You already have a full license, no need to extend trial (thank you for sharing , your share was recorded)", "sample", "error");
                }
                else if (result.db_IsTrial == true && result.db_IsActive == true) {
                    //trial still active
                    var d1 = result.trialEndDate;
                    d1.setDate(d1.getDate() + 1);
                    result.trialEndDate = d1;

                    userInfoStore.put(result);

                    //Update azure mobile service table
                    upDateAzureTable(ids[0], result);
                }
                else if (result.db_IsTrial == true && result.db_IsActive == false) {
                    //trial had expired
                    var d = new Date();
                    var future = new Date();
                    future.setDate(future.getDate() + 1);
                    result.trialStartDate = d;
                    result.trialEndDate = future;
                    result.db_IsActive = true;
                    userInfoStore.put(result);
                    
                    //Update azure mobile service table
                    upDateAzureTable(ids[0], result);

                    loadTrialModeProxyFile();

                    WinJS.log && WinJS.log("Thank You for sharing about the app, Trial period extended by 1 day", "sample", "error");
                }
                else {
                    //no trial version existed
                    WinJS.log && WinJS.log("There is no trial version for this app", "sample", "error");
                }
            }
            else {
                WinJS.log && WinJS.log("First get added to db by getting a trial license", "sample", "error");
            }
        };
    }
}

function searchDataForShares(evt, response) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");
        
        var request = userInfoStore.get(response.id);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }
        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            if (result) {
                WinJS.log && WinJS.log("Total Shares from TrialDB scenario : " + result.Total_Shares + " .", "sample", "error");
            }
            else {
                WinJS.log && WinJS.log("First get added to db by getting a trial license", "sample", "error");
            }
        };
    }
}


function searchDataUserLicenseInfo(evt, response, currentApp) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");
        
        var request = userInfoStore.get(response.id);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }
        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            if (result) {
                var licenseInformation = currentApp.licenseInformation;
                if ((!licenseInformation.isActive || licenseInformation.isTrial) && (result.db_IsTrial || !result.db_IsActive)) {
                    currentApp.requestAppPurchaseAsync(false).done(
                    function () {
                        if (licenseInformation.isActive && !licenseInformation.isTrial) {
                            result.db_IsTrial = false;
                            updateTrialInfo();
                        } else {
                            WinJS.log && WinJS.log("You still have a trial license for this app.", "sample", "error");
                        }
                    },
                    function () {
                        WinJS.log && WinJS.log("The upgrade transaction failed. You still have a trial license for this app.", "sample", "error");
                    });
                } else {
                    WinJS.log && WinJS.log("You already bought this app and have a fully-licensed version.", "sample", "error");
                }

                function updateTrialInfo() {
                    var txn1 = SdkSample.db.transaction(["userInfo"], "readwrite");

                    txn1.oncomplete = function () {
                        // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
                    };
                    txn1.onerror = function () {
                        WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
                    };
                    txn1.onabort = function () {
                        WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
                    };

                    var store = txn1.objectStore("userInfo");

                    if (licenseInformation.isActive && !licenseInformation.isTrial) {
                        store.put(result);

                        //update azure mobile services table
                        upDateAzureTable(response.id, result);                       

                        WinJS.log && WinJS.log("You successfully upgraded your app to the fully-licensed version.", "sample", "status");
                    }
                }
            }
            else {
                WinJS.log && WinJS.log("First get added to db and getting a trial license", "sample", "error");
            }
        };
    }
}

function searchDataForTrialInfo(evt, response) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");
        
        var request = userInfoStore.get(response.id);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }
        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            if (result) {
                if (result.db_IsActive) {
                    if (result.db_IsTrial) {

                        var remainingTrialTime = (result.trialEndDate - new Date()) / 86400000;
                        if (remainingTrialTime <= 0) {

                            result.db_IsActive = false;
                            userInfoStore.put(result);

                            //update mobile services table
                            upDateAzureTable(response.id, result);
                           
                            WinJS.log && WinJS.log("Inactive license: trial time unavailable", "sample", "error");
                            document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";
                        }
                        else {
                            WinJS.log && WinJS.log("You are using a trial version of this app.", "sample", "status");
                        }
                    } else {
                        WinJS.log && WinJS.log("You no longer have a trial version of this app.", "sample", "error");
                    }
                } else {
                    WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
                }
            }
            else {
                WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
            }
        };
    }
}

function searchDataFullLicenseInfo(evt, response) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");

        var request = userInfoStore.get(response.id);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }

        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            if (result) {
                if (result.db_IsActive) {
                    if (result.db_IsTrial) {

                        var remainingTrialTime = (result.trialEndDate - new Date()) / 86400000;
                        if (remainingTrialTime <= 0) {

                            result.db_IsActive = false;
                            userInfoStore.put(result);

                            //update mobile services table
                            upDateAzureTable(response.id, result);

                            WinJS.log && WinJS.log("Inactive license: trial time unavailable", "sample", "error");
                            document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";
                        }
                        else {
                            WinJS.log && WinJS.log("You are using a trial version of this app.", "sample", "status");
                        }
                    } else {
                        WinJS.log && WinJS.log("You are using a fully-licensed version of this app.", "sample", "status");
                    }
                } else {
                    WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
                }
            }
            else {
                WinJS.log && WinJS.log("You don't have an active license for this app.", "sample", "error");
            }
        };
    }
}

function searchDataForLicenseChange(evt, response) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";
        };
        txn.onabort = function () {
            document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";
        };

        var userInfoStore = txn.objectStore("userInfo");

        var request = userInfoStore.get(response.id);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }

        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            if (result) {
                if (result.db_IsActive) {
                    if (result.db_IsTrial) {

                        var remainingTrialTime = (result.trialEndDate - new Date()) / 86400000;
                        if (remainingTrialTime <= 0) {

                            result.db_IsActive = false;
                            userInfoStore.put(result);

                            //update mobile services table
                            upDateAzureTable(response.id, result);

                            WinJS.log && WinJS.log("Inactive license: trial time unavailable", "sample", "error");
                            document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";

                        } else {
                            document.getElementById("currentLicenseMode").innerText = "Current license mode: Trial license";
                        }
                    } else {
                        document.getElementById("currentLicenseMode").innerText = "Current license mode: Full license";
                    }
                } else {
                    document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";
                }
            }
            else {
                document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";
            }
        };
    }
}

function searchDataTrialTimeRemaining(evt, response) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("db entry not found.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("db entry not found.", "sample", "error");
        };

        var userInfoStore = txn.objectStore("userInfo");

        var request = userInfoStore.get(response.id);

        request.onerror = function (e) {
            access_token = null;
        }
        request.onblocked = function (e) {
            access_token = null;
        }

        request.onsuccess = function (e) {
            console.log(e.target.result);
            var result = e.target.result;

            if (result) {
                if (result.db_IsActive) {
                    if (result.db_IsTrial) {

                        var remainingTrialTime = (result.trialEndDate - new Date()) / 86400000;
                        //remainingTrialTime = 0;
                        if (remainingTrialTime <= 0) {

                            result.db_IsActive = false;
                            userInfoStore.put(result);

                            //update mobile services table
                            upDateAzureTable(response.id, result);

                            WinJS.log && WinJS.log("Inactive license: trial time unavailable", "sample", "error");
                            document.getElementById("currentLicenseMode").innerText = "Current license mode: Inactive license";
                        }
                        else {
                            WinJS.log && WinJS.log("You can use this app for " + Math.round(remainingTrialTime) + " more days before the trial period ends.", "sample", "status");
                        }

                    } else {
                        WinJS.log && WinJS.log("You have a full license. The trial time is not meaningful.", "sample", "error");
                    }
                } else {
                    WinJS.log && WinJS.log("Inactive license: trial time unavailable", "sample", "error");
                }
            }
            else {
                WinJS.log && WinJS.log("Inactive license: trial time unavailable", "sample", "error");
            }
        };
    }
}

function addData(evt, response) {
    if (evt.type === "success") {
        var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

        txn.oncomplete = function () {
            //azure mobile service db updation code
            var AzureEntry;
            //read corresponding azure entity if its there
            azure_userInfoTable.where({ fb_id: response.id }).read().done(function (results) {

                if (results.azureId) {
                    AzureEntry = {
                        id: results.azureId,
                        name: entry.name,
                        id_azure: entry.id,//id_azure same as facebook id
                        db_isactive: entry.db_IsActive,
                        db_istrial: entry.db_IsTrial,
                        fb_id: entry.fb_id,
                        total_shares: entry.Total_Shares,
                        trialStartDate: entry.trialStartDate,
                        trialEndDate: entry.trialEndDate
                    }
                    azure_userInfoTable.update(AzureEntry);
                }
                else {
                    AzureEntry = {
                        name: entry.name,
                        id_azure: entry.id,
                        db_isactive: entry.db_IsActive,
                        db_istrial: entry.db_IsTrial,
                        fb_id: entry.fb_id,
                        total_shares: entry.Total_Shares,
                        trialStartDate: entry.trialStartDate,
                        trialEndDate: entry.trialEndDate
                    }
                    azure_userInfoTable.insert(AzureEntry);

                }
                //end of azure mobile service db updation code
            });
            WinJS.log && WinJS.log("Database entry added.", "sample", "status");
            document.getElementById("currentLicenseMode").innerText = "Current license mode: Trial license";
        };
        txn.onerror = function () {
            WinJS.log && WinJS.log("Unable to add to database, db entry may already exist.", "sample", "error");
        };
        txn.onabort = function () {
            WinJS.log && WinJS.log("Unable to add to database, db entry may already exist.", "sample", "error");
        };

        var d = new Date();

        var future = new Date();
        future.setDate(future.getDate() + 30);

        var userInfoStore = txn.objectStore("userInfo");
        var entry = {
            id: response.id,
            name: response.name,
            db_IsActive: true,
            db_IsTrial: true,
            Total_Shares: 0,
            fb_id: response.id,
            trialStartDate: d,
            trialEndDate: future

        }
        var addResult = userInfoStore.add(entry);

        var request = userInfoStore.get(response.id);

        request.onsuccess = function (e) {
            console.log(e.target.result);
        };

        var list = [];

        userInfoStore.openCursor().onsuccess = function (e) {
            var cursor = e.target.result;

            if (cursor) {
                list.push(cursor.value);
                cursor.continue();
            }
            else {
                console.log(list);
            }
        };
    }
}